import os, os.path
from PyQt4 import QtCore, QtGui
import ImageFont


class FontTreeModel(QtCore.QAbstractItemModel):

	def __init__(self, parent=None, folder=None):
		QtCore.QAbstractItemModel.__init__(self, parent)
		self.rootItem = RootItem(["", "Name"])
		if folder:
			self.folder = str(folder)
			self.getFolder(self.folder)

	def getFolder(self, folder):
		'''gets ttf paths from a folder.'''

		self.rootItem.childItems = []
		for item in os.listdir(folder):
			if os.path.splitext(item)[-1].lower() == '.ttf':
				self.rootItem.appendChild(RowItem(item, self.rootItem))
		self.emit(QtCore.SIGNAL("dataChanged()"))

	def columnCount(self, parent):
		if parent.isValid():
			return parent.internalPointer().columnCount()
		else:
			return self.rootItem.columnCount()

	def data(self, index, role):
		if not index.isValid():
			return QtCore.QVariant()

		if role == QtCore.Qt.CheckStateRole:
			if index.internalPointer().isCheckable(index):
				return QtCore.QVariant(index.internalPointer().checkState[index.column()])

		if role == QtCore.Qt.DisplayRole and index.column() == 1:
			item = index.internalPointer()
			fontfile = str(item.data(index.column()))
			font_fullpath = os.path.join(self.folder, fontfile)
			#print font_fullpath
			fontname = "%s [%s]" % ImageFont.truetype(font_fullpath, 10).getname()
			return QtCore.QVariant(QtCore.QString(fontname))

		return QtCore.QVariant()

	def flags(self, index):

		if not index.isValid():
			return QtCore.Qt.ItemIsEnabled

		if index.internalPointer().isCheckable(index):
			return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsUserCheckable

		return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable

	def headerData(self, section, orientation, role):
		if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole:
			return QtCore.QVariant(self.tr(self.rootItem.data(section)))

		return QtCore.QVariant()

	def index(self, row, column, parent):
		if row < 0 or column < 0 or row >= self.rowCount(parent) or column >= self.columnCount(parent):
			return QtCore.QModelIndex()

		if not parent.isValid():
			parentItem = self.rootItem
		else:
			parentItem = parent.internalPointer()

		childItem = parentItem.child(row)
		if childItem:
			return self.createIndex(row, column, childItem)
		else:
			return QtCore.QModelIndex()

	def parent(self, index):
		if not index.isValid():
			return QtCore.QModelIndex()

		childItem = index.internalPointer()
		parentItem = childItem.parent()

		if parentItem == self.rootItem:
			return QtCore.QModelIndex()

		return self.createIndex(parentItem.row(), 0, parentItem)

	def rowCount(self, parent):
		if parent.column() > 0:
			return 0

		if not parent.isValid():
			parentItem = self.rootItem
		else:
			parentItem = parent.internalPointer()

		return parentItem.childCount()

	def setData(self, index, value, role=QtCore.Qt.EditRole):

		if not index.isValid():
			return False

		if role == QtCore.Qt.CheckStateRole:
			item = index.internalPointer()
			if item.isCheckable(index):
				if item.checkState[index.column()] == QtCore.Qt.Unchecked:
					item.checkState[index.column()] = QtCore.Qt.Checked
				else:
					item.checkState[index.column()] = QtCore.Qt.Unchecked
				self.emit(QtCore.SIGNAL("dataChanged(const QModelIndex&, const QModelIndex&)"), index, index)
				return True

		return False


class RootItem(object):

	def __init__(self, text, parent=None):

		self.parentItem = parent
		self.itemData = text
		self.childItems = []

	def appendChild(self, item):

		self.childItems.append(item)

	def child(self, row):

		return self.childItems[row]

	def childCount(self):

		return len(self.childItems)

	def columnCount(self):

		return len(self.itemData)

	def data(self, column):

		return self.itemData[column]

	def parent(self):

		return self.parentItem

	def row(self):

		if self.parentItem:
			return self.parentItem.childItems.index(self)

		return 0

	def isCheckable(self, index):

		return False


class RowItem(RootItem):

	def __init__(self, path, parent):
		#TODO: parse path into name
		RootItem.__init__(self, ["", path], parent)
		self.font_name = path
		self.isChckable = [True, False]
		self.checkState = [False, None]

	def isCheckable(self, index):

		return self.isChckable[index.column()]
